package com.panfeng.xcloud.boss.provider.assets.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.panfeng.xcloud.common.core.enums.ResponseStatusEnum;
import com.panfeng.xcloud.common.core.web.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * springcloud oauth2 资源服务器访问拒绝处理器
 *
 * @author xiaobo
 * @version 1.0
 * @since 2018-12-28
 */
@Slf4j
@Configuration
public class AssetsAccessDeniedHandler implements AccessDeniedHandler {

	@Resource
	private ObjectMapper objectMapper;

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
		log.info("处理权限异常. e={}", e);
		ResponseVO responseVO = new ResponseVO();
		responseVO.setCode(ResponseStatusEnum.UNAUTHORIZED.getCode());
		responseVO.setMessage(ResponseStatusEnum.UNAUTHORIZED.getMessage());
		String json = objectMapper.writeValueAsString(responseVO);
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(json);
	}
}
